package com.zyl.controller;

import com.zyl.dto.LoginUserDto;
import com.zyl.pojo.User;
import com.zyl.service.UserService;
import com.zyl.util.ResultVoUtil;
import com.zyl.vo.ResultVo;
import com.zyl.vo.UserLoginVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: Zyl
 * @Param:
 * @return:
 * @Description:
 */
@RestController
public class UserLoginController {
    @Autowired
    private UserService userService;
    @PostMapping("/login")
    public ResultVo Login(@RequestBody LoginUserDto loginUserDto){
        User user = userService.queryUserByUsername(loginUserDto.getUsername());
        Subject subject= SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken(loginUserDto.getUsername(),loginUserDto.getPassword());
        try{
            subject.login(token);
            String loginUsername = user.getTrueName();
            Integer UserId=user.getId();
            String avarImage = userService.findUserPictureById(UserId);
            UserLoginVo userLoginVo=new UserLoginVo(UserId,loginUsername,avarImage);
            return  ResultVoUtil.success(userLoginVo);
        }catch (UnknownAccountException e){
            //用户名不存在
            return ResultVoUtil.fail("用户名错误");
        }catch (IncorrectCredentialsException e){
            return ResultVoUtil.fail("密码错误");
        }
    }
}
